package com.itlong.cloud.controller.authority;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <desc>
 *      旺龙人脸图片鉴权控制器
 * </desc>
 *
 * @createDate 2020/05/26
 */
@RestController
@RequestMapping("/faceUrl")
public class FaceUrlAuthController {
    private static Logger LOG = LoggerFactory.getLogger(FaceUrlAuthController.class);

    @Value("${" + PlatformConstants.CLOUD_ELEVATOR_AESKEY + "}")
    private  String cloudCloudAeskey; //设备

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;//app,平板

    @Value("${" + PlatformConstants.PROPERTY_OPERATE_MINI_CONTENT_AES_ENCRYPT_KEY + "}")
    String propertyOperateMiniContentAesEncryptKey;//物业,运营,小程序

    @Value("${" + PlatformConstants.SMART_CARD_TOKEN_KEY + "}")
    String userTokenKey;//一卡通

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    /**
     * <desc>
     *      旺龙人脸图片鉴权
     * </desc>
     *
     * @param request
     * @return
     * @author Qiang.S
     * @createDate 2020/05/26
     */
    @RequestMapping("/checkAuth")
    @ResponseBody
    @UnAuthAccessRequired
    public Object checkAuth(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//失败使用401
        //防止跨域问题,变向允许任何请求
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "20000");
        response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String inputStr = request.getHeader("itlong-face-sign");
        //LOG.info("itlong-face-sign:"+inputStr);
        try {
            if (StringUtils.isNotBlank(inputStr)) {//鉴权字段为空跳出
                JSONObject json = JSONObject.parseObject(inputStr);
                //json中必要字段为空跳出
                if (json != null && json.get("datetime") != null && json.get("type") != null) {
                    String encryptTime = null;//入参时间
                    String datetime = json.get("datetime").toString();
                    int type = (int) json.get("type");
                    if (type == 1) {//设备
                        encryptTime = DesEncryptUtil.aesDecrypt(datetime, cloudCloudAeskey);
                    } else if (type == 2 || type == 5) {//平板,app
                        encryptTime = UserTokenUtil.getPassword(datetime, APP_USER_TOKEN_KEY);
                    } else if (type == 3 || type == 4 || type == 6  || type == 9) {//运营,物业,小程序,云端
                        encryptTime = DesEncryptUtil.aesDecrypt(datetime, propertyOperateMiniContentAesEncryptKey);
                    } else if (type == 8) {//一卡通
                        encryptTime = UserTokenUtil.getPassword(datetime,userTokenKey);
                    } else if (type == 7 && json.get("appId") != null) {//sdk
                        PropertyUserInfoPO propertyUserInfoPO = iSDKUserServiceClient.getPropertyUserByAppId(json.get("appId").toString());
                        if (propertyUserInfoPO != null && StringUtils.isNotBlank(propertyUserInfoPO.getAppsecret())) {
                            encryptTime = DesEncryptUtil.aesDecrypt(datetime, propertyUserInfoPO.getAppsecret());
                        }
                    }
                    if (StringUtils.isNotBlank(encryptTime)) {
                        if (type == 7) {//只在SDK时进行时间判断
                            Date inputTime = format.parse(encryptTime);
                            if (inputTime.after(new Date())) {//入参时间小于当前时间放行
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        }else {
                            response.setStatus(HttpServletResponse.SC_OK);
                        }
                    }
                }
            }
        }catch ( Exception e){
            LOG.error("鉴权失败!");
        }
        return "";
    }
}